define(['jquery',"bootstrap","bbcare",
    "scprit/followup/app/prematureOvarianFailure/womenHealthQuestionnaire.ui.js",
    "scprit/followup/app/prematureOvarianFailure/surveyOfWomenHealth.servers.js"
    ],function($,bootstrap,$bb,$ui,$servers){
    var event = {};
    /*
     * 妇女健康调查问卷：
     */
    //添加备注：
    var addRemark = function(){
        var lens = $("#remarks").find("div.remark").length;
        $ui.extralMarkInit({"id":"#remarks","extra":[{"num":lens+1}]});
        $("#remarks script").remove();//删除模板；
    };
    /*
    * 提交：
     */
     var scoreObjDeal_osi = function(scoreObj,infoParams){
        var positionsId = {};
        for(var item in scoreObj["ques"]){
            var items = item.split("-").join('.');
            positionsId[items] = scoreObj["ques"][item].join(";")
        }
        return positionsId;
    };
    var scoreObjDealMark_osi = function(scoreObj){
        var marks = scoreObj["mark"];
        var mark = {};
        for(var id in marks){
            var k = 0;
            mark[id] = [];
            for(var i = 0;i< marks[id].length;i++){
                if(marks[id][i].text){
                    k++;
                    mark[id].push({"num":k,"text":marks[id][i].text});
                }
            }
            if(mark[id].length == 0) delete mark[id];
        }
        return mark;
    };
 var toSubmitFn_osi = function(){
    //提交前的数据处理：
    var params = $(this).data("params");
    var scoreObj = params.scoreObj ;
    var infoParams = params.infoParams;
    var positionsId = scoreObjDeal_osi(scoreObj,infoParams);
    scoreObj["mark"] = scoreObjDealMark_osi(scoreObj);
    var inParams = {
        "userId":infoParams.userId,
        "postionScores":scoreObj,
        "postionIds":positionsId,
        "examinationPaperName": 'DGLE'
    };
    var submitCallback = function(data,params){
        if(data.success){
            $("#myModalBox").find("."+params.className).modal("hide");
            $bb.toastShow("保存成功",1500);
            setTimeout(function(){
                $bb.openPage("prematureOvarianFailureDetail",params);
            },100);
        }else{
            $bb.toastShow(data.msg,1500)
        }
    };
    $servers.saveQuestions(inParams,submitCallback,infoParams);
 };
    /*
    * 上下题目跳转：
     */
    var topicSwitchingOSI = function(questions,scoreObj,dom,infoParams,length){
        var nextList;
        var group = $(dom).attr("group");
        var nowQuesId = $("#questionnaire").find("div[quesType='osi']").attr("id");
        var questionsnaire = $(dom).parents('.questionnaire_operate').siblings(".questionnaire");
        var type = questionsnaire.find('div[quesType="osi"]').attr("type");
        //切题时存储备注内容：
        var mark = [];
        $("#remarks").find("div.remark").each(function(){
            var num = $(this).attr("num");
            var text = $.trim($(this).find("textarea").val());
            mark.push({"num":num,"text":text});
        });
        scoreObj['mark'][nowQuesId] = mark;

        var flag = true;//是否完成；
        if(type == "blank" || type == "blankList"){
            flag = quesBlankFn_osi(scoreObj,dom);
        }else if (type == "single"){
            flag = quesSingleSave_osi(scoreObj,dom);
        }else if (type == "checkbox"){
            flag = quesCheckboxSave_osi(scoreObj,dom);
        }else if(type == "linkage"){
            flag = quesLinkageSaveFn_osi(scoreObj,dom);
        }else{
            if(!scoreObj["ques"][nowQuesId]){
                flag = false;
            }
        }

        var nowList = $("#questionnaire").find("div[quesType='osi']").attr("number");
        nextList = nowList;
        if(group=="prev"){
            if(nowList == "1"){
                $bb.toastShow("目前已经是第一题",1500);
                return;
            }else{
                nextList = nowList*1 - 1;
                flag = true;
            }
        }else if(group=="next"){
            if(flag){
                if(nowList == length){
                    var className = "toSubmitModal";
                    infoParams.className = className;
                    $ui.toSubmitInit({"id":"#myModalBox","data":{"className":className}});
                    $("#myModalBox").find("."+className).modal({"backdrop":'static',"show":true});
                    $ui.lesSubmitInit({
                        "dom":$("."+className).find(".modal-body"),
                        "evaType":infoParams.type
                    });
                    //返回修改：
                    $("#backModify").click(function(){
                        $("#myModalBox").find("."+className).modal("hide");
                    });
                    //去提交：
                    $("#toSubmit").data("params",{"scoreObj":scoreObj,"infoParams":infoParams});
                    $("#toSubmit").click(toSubmitFn_osi);
                }else{
                    nextList = nowList*1 + 1;
                }
            }else{
                $bb.toastShow("当前题目还未做完，不可以进入下一题",2000);
            }
        }
        //渲染记录：
        var nextId = questions[nextList].id;
        var nextType = questions[nextList].type;
        if(nextId){var prefix =nextId.substring(0,1); }
        if(scoreObj['mark'][nextId]){
            questions[nextList].extra = scoreObj['mark'][nextId];
        }
        historyData(scoreObj,questions,nextList,nextId,nextType);
        if(flag){
            $ui.questionTypeInit2({"id":"#questionnaire","data":questions[nextList]});
            var nextGroup = questions[nextList].itemTitle;
            $(".project_schedule").find('li[group="'+nextGroup+'"]').addClass("doing").siblings().removeClass('doing');
            if(nextType == "linkage" || nextType == "blank"){
                historyData2(scoreObj,questions,nextList,nextType);
            }
        }
    };
    var historyData2 = function(scoreObj,questions,nextList,nextType){
        var questionsnaire = $(".questionnaire");
        if(questions[nextList].list){
            questionsnaire.find('.panel-body>div[type]').each(function(){
                var id=$(this).attr("id");
                var type=$(this).attr("type");
                if(type == "blank"){
                    if(scoreObj["ques"][id]){
                        $(this).find("input").each(function(index){
                            $(this).val(scoreObj["ques"][id][index]);
                        });
                    }
                }
            })
        }else if(nextType == "blank"){
            questionsnaire.find('div[type="blank"]').each(function(){
                var id=$(this).attr("id");
                if(scoreObj["ques"][id]){
                    $(this).find("input").each(function(index){
                        $(this).val(scoreObj["ques"][id][index]);
                    });
                }
            });
        }
    }
    var historyData = function(scoreObj,questions,nextList,nextId,nextType){
        delete questions[nextList].value;
        delete questions[nextList].extralSingle;
        delete questions[nextList].valueLens;
        if(scoreObj["ques"][nextId] && scoreObj["ques"][nextId].length > 0){
            if(nextType == "blank"){
                questions[nextList].value = scoreObj["ques"][nextId][0];
            }else if(nextType == "single" || nextType == "checkbox"){
                optionsStatus(questions[nextList],questions[nextList].option,scoreObj["ques"][nextId],nextType)
            }else if(nextType == "blankList"){
                var scoreArr = [];
                var score = scoreObj["ques"][nextId];
                for(var i = 0;i<score.length;i++){
                    scoreArr.push({"no":i+1,"val":score[i]});
                }
                questions[nextList].value = scoreArr;
                questions[nextList].valueLens = scoreArr.length;
            }else if(nextType == "linkage"){
                dealLinkage(scoreObj,questions,nextList,nextId,nextType);
            }
        }else{
            if(nextType == "linkage"){
                dealLinkage(scoreObj,questions,nextList,nextId,nextType);
            }
        }
    }
    var dealLinkage = function(scoreObj,questions,nextList,nextId,nextType){
        for(var i = 0 ;i< questions[nextList].list.length;i++){
            var id = questions[nextList].list[i].id;
            delete questions[nextList].list[i].value;
            delete questions[nextList].list[i].extralSingle;
            delete questions[nextList].list[i].value;
            delete questions[nextList].list[i].valueLens;
            delete questions[nextList].list[i].values;
            if(scoreObj["ques"][id] && scoreObj["ques"][id].length > 0){
                var type = questions[nextList].list[i].type;
                if(type == "blank"){
                    questions[nextList].list[i].value = scoreObj["ques"][id][0];
                }else if(type == "single" || type == "checkbox"){
                    optionsStatus(questions[nextList].list[i],questions[nextList].list[i].option,scoreObj["ques"][id],type)
                }else if(type == "blankList"){
                    var scoreArr = [];
                    var score = scoreObj["ques"][id];
                    if(scoreObj["ques"][id].length > 0){
                        for(var k = 0;k<score.length;k++){
                            scoreArr.push({"no":k+1,"val":score[k]});
                        }
                        questions[nextList].list[i].value = scoreArr;
                        questions[nextList].list[i].valueLens = scoreArr.length;
                    }
                }else if(type == "blankSingle"){
                    var scoreArr = [];
                    var score = scoreObj["ques"][id];
                    var lens = scoreObj["ques"][id].length;
                    if(lens > 0){
                        if(lens > 1){
                            for(var k = 0;k<score.length;k++){
                                if(k!= 0 && k!= (lens-1)){
                                    scoreArr.push({"no":k+1,"val":score[k]});
                                }
                            }
                            for(var item in questions[nextList].list[i].option){
                                if(item == score[lens-1]){
                                    questions[nextList].list[i].flag = 1;
                                }else{
                                    questions[nextList].list[i].flag = 2;
                                }
                            }
                            questions[nextList].list[i].values = scoreArr;
                        }
                        questions[nextList].list[i].value = score[0];
                    }
                }
            }
        }
    }
    /*
    * 遍历选项option，如果选中，flag = 1
     */
    var optionsStatus = function(question,option,value,type){
        for(var i = 0;i<option.length;i++){
            var val = option[i].item;
            if(type =="single"){
                if(val == value[0]){
                    option[i].flag = 1;
                }else{
                    option[i].flag = 2;
                }
                question.extralSingle = value[1];
                question.value = value[0];
            }else if(type == "checkbox"){
                if($.inArray(val,value) >= 0){
                    option[i].flag = 1;
                    question.value = val;
                }else{
                    for(var j = 0;j<value.length;j++){
                        if(value[j].indexOf("--") > 0){
                            var name = value[j].substring(0,value[j].indexOf("--"));
                            if(name == val){
                                option[i].flag = 1;
                                question.extralSingle = value[j].substring(value[j].indexOf("--")+2)
                                question.extralName = name;
                            }
                        }else{
                            option[i].flag = 2;
                        }
                    }
                    
                }
            }
        }
    }
    /*
    *多选 + 输入框的保存：
     */
    var quesCheckboxSave_osi = function(scoreObj,dom){
        var questionsnaire = $(dom).parents('.questionnaire_operate').siblings(".questionnaire");
        var nowId = questionsnaire.find('div[quesType="osi"]').attr("id");
        var flag = true;
        if(questionsnaire.find('div.link_checked').length == 0){
            flag = false;
            return;
        }
        if($("input").length > 0){
            if(!$.trim($("input").val())){
                flag = false;
                return;
            }
        }
        scoreObj["ques"][nowId] = [];
        if(questionsnaire.find('div.link_checked').length > 0 ){
             questionsnaire.find('div.link_checked').each(function(){
                var name = $(this).attr("name");
                if(name.indexOf("其他") == -1){
                    scoreObj["ques"][nowId].push(name);
                }else{
                    if($("input").length > 0){
                        scoreObj["ques"][nowId].push(name+"--"+$.trim($("input").val()));
                    }
                }
            });
        }
        return flag;
    }
    /*
    *  单选题：
     */
    var dealCss = function(link,isShow){
        for(var i = 0;i<link.length;i++){
            if(link[i].indexOf(".")>= 0){
                var splitId = link[i].split(".");
                link[i] = splitId.join("-");
            }
            if(isShow == 1){
                $("#"+ link[i]).attr("must",'1').css("display","block");
            }else{
                $("#"+ link[i]).attr("must",'1').css("display","none");
            }
        }
    }
    var quesSingleSave_osi = function(scoreObj,dom){
        var questionsnaire = $(dom).parents('.questionnaire_operate').siblings(".questionnaire");
        var nowId = questionsnaire.find('div[quesType="osi"]').attr("id");
        var flag = false;
        if(questionsnaire.find('div.link_checked').length == 0){
            flag = false;
            return;
        }
        var name = questionsnaire.find('div.link_checked').attr("name");
        if($("input[name='"+name+"']").length > 0){
            if( !$.trim($("input[name='"+name+"']").val())){
                flag = false;
                return;
            }
            scoreObj["ques"][nowId] = [name,$.trim($("input[name='"+name+"']").val())];
            flag = true;
        }else{
            scoreObj["ques"][nowId] = [name];
            flag = true;
        }
        return flag;
    }
    var quesSingleTabFn_osi = function(scoreObj,dom){
        $(dom).addClass("link_checked").siblings().removeClass("link_checked");
        var html = $(dom).html(),name = $(dom).attr("name");
        var choose=$(dom).parent().attr("choose");
        if(!choose){
            if(html.indexOf("其他") >= 0 ){
                $(dom).parent().siblings(".extralSingle").html('请填写：<input type="text" class="form-control w-150" name="'+name+'">');
                $("input[name='"+name+"']").focus();
                $("input[name='"+name+"']").blur(function(){
                    if(!$(this).val()){
                        $(this).focus();
                    }
                });
            }else{
                $(dom).parent().siblings(".extralSingle").html("");
            }
        }
    };
    var quesCheckboxTabFn_osi = function(scoreObj,dom){
        var html = $(dom).html(),name = $(dom).attr("name");
        var choose=$(dom).parent().attr("choose");
        if(choose){var link=JSON.parse($(dom).parent().attr("link")); }
        if($(dom).hasClass("link_checked")){
            $(dom).removeClass("link_checked");
            if(choose){
                if(choose.indexOf(name) != -1){
                    if(choose.indexOf(';') > 0 && choose.indexOf(name+";") != -1){
                        dealCss(link);
                    }else if(choose == name){
                        dealCss(link);
                    }
                }
            }else{
                if(html.indexOf("其他") >= -1 ){
                    $(dom).parent().siblings(".extralSingle").html("");
                }
            }
        }else{
            $(dom).addClass("link_checked");
            if(choose){
                if(choose.indexOf(name) != -1){
                    if(choose.indexOf(';') > 0 ){
                        dealCss(link,1);
                    }else if(choose == name){
                        dealCss(link,1);
                    }
                }
            }else{
                if(html.indexOf("其他") >= 0 ){
                    $(dom).parent().siblings(".extralSingle").html('请填写：<input type="text" class="form-control w-150" name="'+name+'">');
                    $("input[name='"+name+"']").focus();
                }
            }
            
        }
    }
    /*
    * osi填空题：
     */
    var quesBlankFn_osi = function(scoreObj,dom){
        var questionsnaire = $(dom).parents('.questionnaire_operate').siblings(".questionnaire");
        var type = questionsnaire.find('div[quesType="osi"]').attr("type");
        var nowId = questionsnaire.find('div[quesType="osi"]').attr("id");
        if(type == "blank"){
            var flag = true;//判断是否填完：
            scoreObj["ques"][nowId] = [];
            questionsnaire.find('div[quesType="osi"]').find('.panel-body input').each(function(){
                if(!$(this).val()){
                    flag = false;
                    return;
                }
            });
            questionsnaire.find('div[quesType="osi"]').find('.panel-body input').each(function(){
                scoreObj["ques"][nowId].push($(this).val());
            });
        }else if(type=="blankList"){
            var flag = false;//判断是否填完：
            scoreObj["ques"][nowId] = [];
            questionsnaire.find('div[quesType="osi"]').find('.panel-body textarea').each(function(){
                if($(this).val()){
                    flag = true;
                    return;
                }
            });
            questionsnaire.find('div[quesType="osi"]').find('.panel-body textarea').each(function(){
                if($(this).val()){
                    scoreObj["ques"][nowId].push($(this).val());
                }
            });
            if(nowId == "I3" && scoreObj["ques"]["I2"]){//如果I2选择d/e;I3必填：
                if(scoreObj["ques"]["I2"][0] != "d" && scoreObj["ques"]["I2"][0] != "e"){
                    flag = true;
                }
            }
        }
        return flag;
    }
    //osi_blankList:
    var addBlankFn = function(scoreObj,dom){
        if(!$(dom).prev('textarea').val()){
            $bb.toastShow("当前输入框还未填写",2000);
            return;
        }
        var h = '<div class="clearfix"><textarea class="pull-left form-control blank_text"></textarea><button class="pull-left btn btn-pri" id="addBlank">添加</button></div>';
        $(dom).parents("div.blankList").append(h);
        $(dom).remove();
    }
    /*
    * 联动 + 单选+填空+多选：
     */
    var quesLinkageSaveFn_osi = function(scoreObj,dom){
        var questionsnaire = $(dom).parents('.questionnaire_operate').siblings(".questionnaire");
        questionsnaire.find('.panel-body>div[type]').each(function(){
            var nowId = $(this).attr("id");
            var type = $(this).attr("type");
            //存储：
            if(type == "single"){
                if($(this).find('div.link_checked').attr("name")){
                    scoreObj["ques"][nowId] = [$(this).find('div.link_checked').attr("name")]
                }
            }else if(type == "checkbox"){
                if($(this).find('div.link_checked').length > 0 ){
                    scoreObj["ques"][nowId] = [];
                     $(this).find('div.link_checked').each(function(){
                        scoreObj["ques"][nowId].push($(this).attr("name"));
                    });
                }
            }else if(type == "blankList"){
                var isFlag = false;
                scoreObj["ques"][nowId] = [];
                $(this).find('textarea').each(function(){
                    if(!isFlag){
                        if($(this).val()){isFlag = true;}
                    }
                    scoreObj["ques"][nowId].push($(this).val());
                    
                });
                if(!isFlag){
                    delete scoreObj["ques"][nowId];
                }
            }else if(type == "blank"){
                scoreObj["ques"][nowId] = [];
                var isFlag = true;
                $(this).find('input').each(function(){
                    if(isFlag){
                        if(!$(this).val() && $(this).val().length == 0){isFlag = false;}
                    }
                    scoreObj["ques"][nowId].push($(this).val());
                });
                if(!isFlag){
                    delete scoreObj["ques"][nowId];
                }
            }else if(type=="blankSingle"){
                scoreObj["ques"][nowId] = [];
                var isFlag = true,isEnding = true;
                $(this).find('input').each(function(){
                    if(isFlag){
                        if(!$(this).val() && $(this).val().length == 0){isFlag = false;}
                    }
                    scoreObj["ques"][nowId].push($(this).val());
                });
                if(!isFlag){
                    delete scoreObj["ques"][nowId];
                }else{
                    if($(this).find('div.link_checked').attr("name")){
                        scoreObj["ques"][nowId].push($(this).find('div.link_checked').attr("name"));
                    }
                }
            }
        });
        //判断是否做完：
        var flag = true;
        questionsnaire.find('.panel-body>div[type]').each(function(){
            var nowId = $(this).attr("id");
            var type = $(this).attr("type");
            if(type != "blankSingle"){
                var hasStyle = $(this).attr("style");
                if(!hasStyle){//没有style属性：必填项：
                    if(!scoreObj["ques"][nowId]){
                        flag = false;
                        return;
                    }
                }else{ //具有style属性
                    var css = $(this).css("display");
                    if(css == "block"){
                        if(!scoreObj["ques"][nowId]){
                            flag = false;
                            return
                        }
                    }else if(css == "none"){
                        delete scoreObj["ques"][nowId];
                    }
                }
            }else{
                var inputVal = $(this).find(".ques").find("input[type='number']").val();
                if(inputVal == '0'){
                    flag = true;
                }else{
                    $(this).find('.inputNo').find("input").each(function(){
                        if(!$(this).val() && $(this).val().length == 0){
                            flag = false;
                            return;
                        }
                    });
                    if($(this).find('div.link_checked').length == 0){
                        flag = false;
                        return;
                    }
                }
            }

        });
        return flag;
    }
    var quesLinkageTabFn_osi = function(scoreObj,dom){
        var choose=$(dom).parent().attr("choose");
        if(choose){
            var name = $(dom).attr("name");
            if(choose.indexOf("[") >= 0 && choose.indexOf("]") >= 0){
                var chooseArr = JSON.parse(choose);
                var index = $.inArray(name,chooseArr);
                var link0=JSON.parse($(dom).parent().attr("link0"));
                var link1=JSON.parse($(dom).parent().attr("link1"));
                if(choose.indexOf(name) != -1){
                    if(index == 0){
                        dealCss(link1);
                        dealCss(link0,1);
                    }else if(index == 1){
                        dealCss(link0);
                        dealCss(link1,1);
                    }
                }else{
                    dealCss(link1);
                    dealCss(link0);
                }
            }else{
                var link=JSON.parse($(dom).parent().attr("link"));
                if(choose.indexOf(name) != -1){
                    if(choose.indexOf(';') > 0){
                        dealCss(link,1);
                    }else if(choose == name){
                        dealCss(link,1);
                    }else{
                        dealCss(link);
                    }
                }else{
                    dealCss(link);
                }
            }


        }
    }
    /*
    * singleBlank：
     */
    var singleBlankClick_osi = function(scoreObj,dom){
        $(dom).addClass("link_checked").siblings().removeClass("link_checked");
    };
    var singleBlankInput_osi = function(scoreObj,dom){
        if($(dom).val() && $(dom).val()!= "0"){
            var h= '';
            for(var i = 0 ; i<$(dom).val();i++){
                h +='<input class="form-control w-150" type="date" name="singleNo">';
            }
            $(dom).parent().siblings(".inputNo").html(h).css("display","block");
            $(dom).parent().siblings(".ques_single_tab").css("display","block");
        }else{
            $(dom).parent().siblings(".inputNo").html('').css("display","none");
            $(dom).parent().siblings(".ques_single_tab").css("display","none");
        }
    };
    //妇女健康调查问卷：
    event.init2 = function(questions,scoreObj,infoParams,length){
        //添加备注：
        $("#box").on("click","#add_remark_btn",addRemark);

        //上下题切换：
        $("#box").on("click",".ques-click button",function(){
            var _this = this;
            topicSwitchingOSI(questions,scoreObj,_this,infoParams,length);
        });

        /*
        * OSI单选：single
        * */
        $("#box").on("click","div[type='single'] .linkage_tab",function(){
            var _this = this;
            quesSingleTabFn_osi(scoreObj,_this);
        });
        /*
        * OSI多选：checkbox
        * */
        $("#box").on("click","div[type='checkbox'] .linkage_tab",function(){
            var _this = this;
            quesCheckboxTabFn_osi(scoreObj,_this);
        });
        /*
        * OSI填空：blankList //上翻时遍历保存；
        * */
        $("#box").on("click","div[type='blankList'] #addBlank",function(){
            var _this = this;
            addBlankFn(scoreObj,_this);
        });
        $("#box").on("blur","div[type='blank'][quesType='osi'] input[type='number']",function(){
            if($(this).val() < 0){
                $bb.toastShow("不可以输入小于0的值");
                $(this).val('').focus();
            }
        });

        /*
        * 联动题型：单选点击事件：
         */
        $("#box").on("click","div[type='linkage'] div[type='single'] .linkage_tab",function(){
            var _this = this;
            quesLinkageTabFn_osi(scoreObj,_this);
        });
        /*
        * singleBlank:试管婴儿技术：
        * */
        $("#box").on("blur","div[type='linkage'] div[type='blankSingle'] input[type='number']",function(){
            var _this = this;
            singleBlankInput_osi(scoreObj,_this);
        });
        $("#box").on("click","div[type='linkage'] div[type='blankSingle'] .linkage_tab",function(){
            var _this = this;
            singleBlankClick_osi(scoreObj,_this);
        });

        /*
        * 右侧列表点击事件：
        * */
        $(".project_schedule").off("click","li");
        $(".project_schedule").on("click","li",function(){
            $(this).addClass("doing").siblings().removeClass("doing");
            var group = $(this).attr("group");
            var num = 1;
            if(group == '月经婚育史'){
                num = 1;
            }else if(group == '既往避孕措施情况'){
                num = 14;
            }else if(group == '近1年内是否出现以下症状'){
                num = 15;
            }else if(group == "妇科及既往疾病史"){
                num = 23;
            }else if(group == "家族史"){
                num = 31;
            }else if(group == "是否诊断为卵巢早衰或卵巢功能减退"){
                num = 32;
            }
            historyData(scoreObj,questions,num,questions[num].id,questions[num].type);
            $ui.questionTypeInit2({"id":"#questionnaire","data":questions[num]});
            historyData2(scoreObj,questions,num,questions[num].type);
        });
        $(".project_schedule li").eq(0).click();
    };
    return event;
});